<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>栈的思维算法</title>
</head>
<body>
	<script type="text/javascript">
		document.write('栈的思维算法');


    // 题目：编写“智能重复”smartRepeat函数，实现：
    //  ——将'3[abc]'变成'abcabcabc'
    //  ——将'3[2[a]2[b]]'变成'aabbaabbaabb'
    //  ——将'3[1[a]3[b]2[3[c]4[d]]]'变成'abbbcccddddcccddddabbbcccddddcccddddabbbcccddddcccdddd'
 
    let str ='33[1[a]3[b]2[3[c]4[d]]]';
      function smartRepeat(templateStr){
      	//指针
      	let index =0;
      	//存放数字的栈stack1
      	let stack1 =[];
      	//存放字母的栈Stack2
      	let stack2 =[];
      	//剩余部分
      	let rest = templateStr;
      	//while循环
      	while(index<templateStr.length-1){
      		//剩余部分
      		rest = templateStr.substring(index);
      		//如果剩余部分是数字开头
      		if(/^\d+\[/.test(rest)){
      			// console.log(rest.match(/^(\d+)\[/))
      			//将数字压入栈stack1
      			stack1.push(Number(rest.match(/^(\d+)\[/)[1]));
      			//将空字符串压入栈stack2
      			stack2.push('')
      			//指针增加数字的长度+1，加一是因为一个【
      			let times =rest.match(/^(\d+)\[/)[1].length +1;
      			index += times;
      		}else if(/^\w+/.test(rest)){
      			//如果这个字符是字母就替换掉Stack2的栈顶项
      			let word = rest.match(/^\w+/)[0];
      			// console.log(word)
      			stack2[stack2.length-1] = word;
      			// 指针后移，后移的位数是word的长度
      			index += word.length;

      		}else if(/^\]/.test(rest)){
      			//当是以】开头时那么就stack1和stack2最后一项都出栈，并且stack2的出栈的字母重复stack1数字次数拼接到新stack2栈顶项上
      			let times = stack1.pop();
      			let num = stack2.pop();
      			stack2[stack2.length-1] += num.repeat(times);
                index++
      		}
      		console.log(index,stack1,stack2)
      		
      	}

      }



      smartRepeat(str)


	</script>
	
</body>
</html>